import json  
  
def load_tasks():  
    try:  
        with open('tasks.json', 'r') as file:  
            tasks = json.load(file)  
    except FileNotFoundError:  
        # 如果文件不存在，则创建一个空的任务列表  
        tasks = []  
    except json.JSONDecodeError:  
        # 如果文件内容不是有效的JSON，则也创建一个空的任务列表  
        tasks = []  
    return tasks  
  
def save_tasks(tasks):  
    with open('tasks.json', 'w') as file:  
        json.dump(tasks, file, indent=4)  
  
def add_task(tasks, task_description):  
    task = {'description': task_description, 'completed': False}  
    tasks.append(task)  
    save_tasks(tasks)  
    print(f"Task '{task_description}' added.")  
  
def view_tasks(tasks):  
    if not tasks:  
        print("No tasks to display.")  
        return  
      
    print("Tasks:")  
    for index, task in enumerate(tasks, start=1):  
        status = "✓" if task['completed'] else "✗"  
        print(f"{index}. {status} {task['description']}")  
  
def complete_task(tasks, task_index):  
    try:  
        task = tasks[task_index - 1]  
        task['completed'] = True  
        save_tasks(tasks)  
        print(f"Task '{task['description']}' completed.")  
    except IndexError:  
        print(f"Error: Task index {task_index} out of range.")  
  
def delete_task(tasks, task_index):  
    try:  
        del tasks[task_index - 1]  
        save_tasks(tasks)  
        print("Task deleted.")  
    except IndexError:  
        print(f"Error: Task index {task_index} out of range.")  
  
def main():  
    tasks = load_tasks()  
      
    while True:  
        print("\nToDo List")  
        print("1. Add Task")  
        print("2. View Tasks")  
        print("3. Complete Task")  
        print("4. Delete Task")  
        print("5. Exit")  
          
        choice = input("Enter your choice: ")  
          
        if choice == '1':  
            task_description = input("Enter task description: ")  
            add_task(tasks, task_description)  
        elif choice == '2':  
            view_tasks(tasks)  
        elif choice == '3':  
            task_index = int(input("Enter task index to complete: "))  
            complete_task(tasks, task_index)  
        elif choice == '4':  
            task_index = int(input("Enter task index to delete: "))  
            delete_task(tasks, task_index)  
        elif choice == '5':  
            print("Exiting...")  
            break  
        else:  
            print("Invalid choice. Please try again.")  
  
if __name__ == "__main__":  
    main()